/*
 * inicializacion.c
 *
 *  Created on: 09/10/2011
 *      Author: Normandia
 *
 */

#include "inicializacion.h"

void leerBootSector(){
	cache_boot_sector = malloc(SECTOR_SIZE * 2);
	readSector(0,cache_boot_sector);

	readSector(cache_boot_sector->n_sector_fs_info,((void*)cache_boot_sector)+SECTOR_SIZE);

	cache_boot_sector->free_clusters = -1;
}

void leerFat() {

	uint32_t fat_pos,fat_size,i;

	fat_pos = cache_boot_sector->n_reserved_sector;
	fat_size = cache_boot_sector->n_sectors_per_fat;

	cache_fat = malloc(fat_size * SECTOR_SIZE);
	for(i=0;i<fat_size;i++){
		readSector(fat_pos + i, cache_fat + SECTOR_SIZE * i /4);
	}
}

void escribirFat() {

	uint32_t fat_pos,fat_size,i;

	fat_pos = cache_boot_sector->n_reserved_sector;
	fat_size = ceil(cache_boot_sector->n_sectors_per_fat * 4 / SECTOR_SIZE);

	for(i=0;i<fat_size;i++){
		writeSector(fat_pos + i, cache_fat + SECTOR_SIZE * i /4);
	}
}

void ObtenerClusterLibres(){

	uint64_t i,fat_size;
	NODELIBREPTR ptr_pie, ptr_nuevo;

	ptrListaSectLibre = collection_queue_create();

	ptr_pie = NULL;

	fat_size = cache_boot_sector->n_sectors_per_fat * SECTOR_SIZE / 4; //funcion que calcula el tamaño de la tabla

	for(i=0;i<fat_size;i++){
		if(cache_fat[i] == 0){

			ptr_nuevo = malloc(sizeof(LISTNODELIBRE));
			ptr_nuevo->n_cluster = i;

			/*if(!ptr_pie){
				ptrListaSectLibre = ptr_pie = ptr_nuevo;
			}else{
				ptr_pie->nextPtr = ptr_nuevo;
				ptr_pie = ptr_nuevo;
			}*/
			collection_queue_push(ptrListaSectLibre,ptr_nuevo);
		}
	}
}

void agregarClusterLibre(uint32_t cluster){

	NODELIBREPTR ptr_nuevo;

	ptr_nuevo = malloc(sizeof(LISTNODELIBRE));

	ptr_nuevo->n_cluster = cluster;
	collection_queue_push(ptrListaSectLibre,ptr_nuevo);

}
